import { ref, reactive } from 'vue'

// 仪表板统计数据
const dashboardStats = reactive({
  bankData: {
    today: 0,
    total: 0,
    trend: '+0% 环比'
  },
  orderData: {
    today: 0,
    total: 0,
    trend: '+0% 环比'
  },
  invoiceData: {
    today: 0,
    total: 0,
    trend: '+0% 环比'
  },
  total: {
    today: 0,
    total: 0,
    trend: '+0% 环比'
  }
})

// 数据源状态
const dataSourceStatus = reactive({
  bank: {
    name: '🏦 银行流水',
    enabled: true,
    lastSync: '2023-10-27 15:30',
    status: 'success', // success, warning, error, none
    uploadCount: 0,
    successCount: 0
  },
  salesOrder: {
    name: '💰 销售订单',
    enabled: true,
    lastSync: '2023-10-27 15:30',
    status: 'success',
    uploadCount: 0,
    successCount: 0
  },
  purchaseOrder: {
    name: '🛒 采购订单',
    enabled: true,
    lastSync: '2023-10-27 15:30',
    status: 'success',
    uploadCount: 0,
    successCount: 0
  },
  incomingInvoice: {
    name: '📥 进项发票',
    enabled: true,
    lastSync: '2023-10-27 15:30',
    status: 'success',
    uploadCount: 0,
    successCount: 0
  },
  outgoingInvoice: {
    name: '📤 销项发票',
    enabled: true,
    lastSync: '2023-10-27 15:30',
    status: 'success',
    uploadCount: 0,
    successCount: 0
  },
  announcement: {
    name: '📢 公告信息',
    enabled: true,
    lastSync: '2023-10-27 15:30',
    status: 'success',
    uploadCount: 0,
    successCount: 0
  }
})

// 同步历史记录
const syncHistory = ref([])

// URL匹配函数
function isUrlMatch(url: string, pattern: string, matchType?: string): boolean {
  // 如果没有指定匹配类型，默认使用includes
  if (!matchType || matchType === 'includes') {
    return url.includes(pattern);
  }
  
  // 精确匹配
  if (matchType === 'exact') {
    // 移除查询参数后进行精确匹配
    const urlWithoutQuery = url.split('?')[0];
    return urlWithoutQuery === pattern;
  }
  
  // 前缀匹配
  if (matchType === 'startsWith') {
    return url.startsWith(pattern);
  }
  
  // 后缀匹配
  if (matchType === 'endsWith') {
    return url.endsWith(pattern);
  }
  
  // 正则表达式匹配
  if (matchType === 'regex') {
    try {
      const regex = new RegExp(pattern);
      return regex.test(url);
    } catch (e) {
      console.error('❌ 正则表达式错误:', pattern, e);
      return false;
    }
  }
  
  // 默认使用includes
  return url.includes(pattern);
}

// 获取真实仪表板数据
const fetchDashboardData = async () => {
  try {
    // 获取拦截的请求数据和拦截规则
    chrome.storage.local.get(['capturedRequests', 'interceptionRules'], (result) => {
      // 确保dashboardStats存在且有正确的结构
      if (!dashboardStats || typeof dashboardStats !== 'object') {
        Object.assign(dashboardStats, {
          bankData: {
            today: 0,
            total: 0,
            trend: '+0% 环比'
          },
          orderData: {
            today: 0,
            total: 0,
            trend: '+0% 环比'
          },
          invoiceData: {
            today: 0,
            total: 0,
            trend: '+0% 环比'
          },
          total: {
            today: 0,
            total: 0,
            trend: '+0% 环比'
          }
        });
      } else {
        // 确保所有必需的属性都存在
        if (!dashboardStats.bankData) {
          dashboardStats.bankData = {
            today: 0,
            total: 0,
            trend: '+0% 环比'
          };
        }
        if (!dashboardStats.orderData) {
          dashboardStats.orderData = {
            today: 0,
            total: 0,
            trend: '+0% 环比'
          };
        }
        if (!dashboardStats.invoiceData) {
          dashboardStats.invoiceData = {
            today: 0,
            total: 0,
            trend: '+0% 环比'
          };
        }
        if (!dashboardStats.total) {
          dashboardStats.total = {
            today: 0,
            total: 0,
            trend: '+0% 环比'
          };
        }
      }
      
      // 确保dataSourceStatus存在且有正确的结构
      if (!dataSourceStatus || typeof dataSourceStatus !== 'object') {
        Object.assign(dataSourceStatus, {
          bank: {
            name: '🏦 银行流水',
            enabled: true,
            lastSync: '2023-10-27 15:30',
            status: 'success',
            uploadCount: 0,
            successCount: 0
          },
          salesOrder: {
            name: '💰 销售订单',
            enabled: true,
            lastSync: '2023-10-27 15:30',
            status: 'success',
            uploadCount: 0,
            successCount: 0
          },
          purchaseOrder: {
            name: '🛒 采购订单',
            enabled: true,
            lastSync: '2023-10-27 15:30',
            status: 'success',
            uploadCount: 0,
            successCount: 0
          },
          incomingInvoice: {
            name: '📥 进项发票',
            enabled: true,
            lastSync: '2023-10-27 15:30',
            status: 'success',
            uploadCount: 0,
            successCount: 0
          },
          outgoingInvoice: {
            name: '📤 销项发票',
            enabled: true,
            lastSync: '2023-10-27 15:30',
            status: 'success',
            uploadCount: 0,
            successCount: 0
          },
          announcement: {
            name: '📢 公告信息',
            enabled: true,
            lastSync: '2023-10-27 15:30',
            status: 'success',
            uploadCount: 0,
            successCount: 0
          }
        });
      }
      
      if (!result) {
        console.log('存储结果为空');
        return;
      }
      
      // 获取拦截规则
      let interceptionRules: any[] = [];
      if (result.interceptionRules) {
        interceptionRules = Array.isArray(result.interceptionRules) ? result.interceptionRules : Object.values(result.interceptionRules);
        console.log('更新拦截规则:', interceptionRules);
      }
      
      // 获取拦截数据
      if (!result.capturedRequests) {
        console.log('没有找到capturedRequests键');
        return;
      }
      
      const interceptedData: any[] = Array.isArray(result.capturedRequests) ? result.capturedRequests : [];
      console.log('拦截数据数组长度:', interceptedData.length);
      
      if (interceptedData.length === 0) {
        console.log('拦截数据为空数组');
        return;
      }
      
      console.log('获取到拦截数据:', interceptedData.length, '条');
      
      // 初始化计数器
      const counts = {
        bank: { today: 0, total: 0 },
        salesOrder: { today: 0, total: 0 },
        purchaseOrder: { today: 0, total: 0 },
        incomingInvoice: { today: 0, total: 0 },
        outgoingInvoice: { today: 0, total: 0 },
        announcement: { today: 0, total: 0 },
        other: { today: 0, total: 0 }
      };
      
      // 获取今天的日期字符串
      const today = new Date().toDateString();
      
      // 遍历所有拦截数据进行分类统计
      interceptedData.forEach((item: any) => {
        console.log('处理数据项:', item);
        // 确定数据类型
        let dataType = 'other';
        
        // 根据拦截规则匹配数据类型
        for (const rule of interceptionRules) {
          if (rule.enabled !== false && item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
            console.log('匹配到规则:', rule.name, '数据类型:', rule.dataType);
            // 根据规则的数据类型字段确定数据类型
            if (rule.dataType) {
              dataType = rule.dataType;
            } else {
              // 根据规则名称确定数据类型
              if (rule.name.includes('银行')) {
                dataType = 'bank';
              } else if (rule.name.includes('订单') && rule.name.includes('采购')) {
                dataType = 'purchaseOrder';
              } else if (rule.name.includes('订单')) {
                dataType = 'salesOrder';
              } else if (rule.name.includes('进项')) {
                dataType = 'incomingInvoice';
              } else if (rule.name.includes('销项')) {
                dataType = 'outgoingInvoice';
              } else if (rule.name.includes('公告')) {
                dataType = 'announcement';
              }
            }
            break;
          }
        }
        
        // 如果没有匹配到规则，尝试根据URL模式判断
        if (dataType === 'other' && item.url) {
          console.log('根据URL模式判断数据类型:', item.url);
          if (item.url.includes('/uc-server/service/hzDealDetailReport/hzDealDetailQuery')) {
            dataType = 'bank';
          } else if (item.url.includes('/api/mall/order/list')) {
            dataType = 'salesOrder';
          } else if (item.url.includes('/szzhzz/qlfpcx/v1/queryFpjcxx')) {
            dataType = 'incomingInvoice';
          } else if (item.url.includes('/szzhzz/fpxxcx/v1/queryFpxx')) {
            dataType = 'outgoingInvoice';
          } else if (item.url.includes('/announcement/lobby/queryPage')) {
            dataType = 'announcement';
          }
        }
        
        console.log('最终数据类型:', dataType);
        
        // 统计总量
        counts[dataType as keyof typeof counts].total++;
        
        // 统计今日数据
        if (item.timestamp && new Date(item.timestamp).toDateString() === today) {
          counts[dataType as keyof typeof counts].today++;
        }
      });
      
      console.log('分类统计结果:', counts);
      
      // 更新仪表板统计数据
      dashboardStats.bankData.today = counts.bank.today;
      dashboardStats.bankData.total = counts.bank.total;
      
      dashboardStats.orderData.today = counts.salesOrder.today + counts.purchaseOrder.today;
      dashboardStats.orderData.total = counts.salesOrder.total + counts.purchaseOrder.total;
      
      dashboardStats.invoiceData.today = counts.incomingInvoice.today + counts.outgoingInvoice.today;
      dashboardStats.invoiceData.total = counts.incomingInvoice.total + counts.outgoingInvoice.total;
      
      dashboardStats.total.today = counts.bank.today + counts.salesOrder.today + counts.purchaseOrder.today + 
                                  counts.incomingInvoice.today + counts.outgoingInvoice.today + counts.announcement.today;
      dashboardStats.total.total = interceptedData.length;
      
      console.log('更新后的仪表板统计数据:', dashboardStats);
      
      // 更新数据源状态（这里简化处理，实际应根据同步状态判断）
      dataSourceStatus.bank.uploadCount = counts.bank.total;
      dataSourceStatus.bank.successCount = Math.max(0, counts.bank.total - Math.floor(counts.bank.total * 0.02));
      
      dataSourceStatus.salesOrder.uploadCount = counts.salesOrder.total;
      dataSourceStatus.salesOrder.successCount = Math.max(0, counts.salesOrder.total - Math.floor(counts.salesOrder.total * 0.02));
      
      dataSourceStatus.purchaseOrder.uploadCount = counts.purchaseOrder.total;
      dataSourceStatus.purchaseOrder.successCount = Math.max(0, counts.purchaseOrder.total - Math.floor(counts.purchaseOrder.total * 0.02));
      
      dataSourceStatus.incomingInvoice.uploadCount = counts.incomingInvoice.total;
      dataSourceStatus.incomingInvoice.successCount = Math.max(0, counts.incomingInvoice.total - Math.floor(counts.incomingInvoice.total * 0.02));
      
      dataSourceStatus.outgoingInvoice.uploadCount = counts.outgoingInvoice.total;
      dataSourceStatus.outgoingInvoice.successCount = Math.max(0, counts.outgoingInvoice.total - Math.floor(counts.outgoingInvoice.total * 0.02));
      
      dataSourceStatus.announcement.uploadCount = counts.announcement.total;
      dataSourceStatus.announcement.successCount = Math.max(0, counts.announcement.total - Math.floor(counts.announcement.total * 0.02));
      
      // 生成同步历史记录
      const history = [];
      let id = 1;
      
      // 按时间分组，创建同步记录
      const groupedByDate: any = {};
      interceptedData.forEach((item: any) => {
        const date = new Date(item.timestamp).toDateString();
        if (!groupedByDate[date]) {
          groupedByDate[date] = [];
        }
        groupedByDate[date].push(item);
      });
      
      // 为每个日期创建同步记录
      Object.keys(groupedByDate).slice(0, 5).forEach(date => {
        const items = groupedByDate[date];
        
        // 分类统计
        const bankItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为银行数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && rule.dataType === 'bank' && item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true;
            }
          }
          return item.url && item.url.includes('/uc-server/service/hzDealDetailReport/hzDealDetailQuery');
        });
        
        const salesOrderItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为销售订单数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && rule.dataType === 'sales_order' && item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true;
            }
          }
          return item.url && item.url.includes('/api/mall/order/list') && !item.url.includes('purchase');
        });
        
        const purchaseOrderItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为采购订单数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && rule.dataType === 'purchase_order' && item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true;
            }
          }
          return item.url && (item.url.includes('purchase') || item.url.includes('procurement'));
        });
        
        const incomingInvoiceItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为进项发票数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && rule.dataType === 'incoming_invoice' && item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true;
            }
          }
          return item.url && item.url.includes('/szzhzz/qlfpcx/v1/queryFpjcxx');
        });
        
        const outgoingInvoiceItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为销项发票数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && rule.dataType === 'outgoing_invoice' && item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true;
            }
          }
          return item.url && item.url.includes('/szzhzz/fpxxcx/v1/queryFpxx');
        });
        
        const announcementItems = items.filter((item: any) => {
          // 根据规则或URL判断是否为公告数据
          for (const rule of interceptionRules) {
            if (rule.enabled !== false && rule.dataType === 'announcement' && item.url && isUrlMatch(item.url, rule.urlPattern, rule.matchType)) {
              return true;
            }
          }
          return item.url && item.url.includes('/announcement/lobby/queryPage');
        });
        
        // 创建同步记录
        if (bankItems.length > 0) {
          history.push({
            id: id++,
            type: '🏦 银行流水',
            timestamp: new Date(bankItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: bankItems.length
          });
        }
        
        if (salesOrderItems.length > 0) {
          history.push({
            id: id++,
            type: '💰 销售订单',
            timestamp: new Date(salesOrderItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: salesOrderItems.length
          });
        }
        
        if (purchaseOrderItems.length > 0) {
          history.push({
            id: id++,
            type: '🛒 采购订单',
            timestamp: new Date(purchaseOrderItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: purchaseOrderItems.length
          });
        }
        
        if (incomingInvoiceItems.length > 0) {
          history.push({
            id: id++,
            type: '📥 进项发票',
            timestamp: new Date(incomingInvoiceItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: incomingInvoiceItems.length
          });
        }
        
        if (outgoingInvoiceItems.length > 0) {
          history.push({
            id: id++,
            type: '📤 销项发票',
            timestamp: new Date(outgoingInvoiceItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: outgoingInvoiceItems.length
          });
        }
        
        if (announcementItems.length > 0) {
          history.push({
            id: id++,
            type: '📢 公告信息',
            timestamp: new Date(announcementItems[0].timestamp).toLocaleString('zh-CN'),
            message: `同步成功`,
            success: true,
            count: announcementItems.length
          });
        }
      });
      
      // 按时间倒序排列
      syncHistory.value = history.sort((a: any, b: any) => 
        new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
      ).slice(0, 5);
      
      console.log('更新后的仪表板数据:', dashboardStats);
      console.log('更新后的数据源状态:', dataSourceStatus);
      console.log('更新后的同步历史:', syncHistory.value);
    });
  } catch (error) {
    console.error('获取仪表板数据失败:', error);
  }
}

// 初始化数据
const initDashboardData = () => {
  fetchDashboardData();
  // 每5秒更新一次数据
  const intervalId = window.setInterval(fetchDashboardData, 5000);
  return intervalId;
}

export function useDashboardData() {
  return {
    dashboardStats,
    dataSourceStatus,
    syncHistory,
    fetchDashboardData,
    initDashboardData
  }
}